package com.zjc.agent.ai.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Map;

/**
 * 通用HTTP请求工具类
 */
@Slf4j
public class HttpUtil {

    private static final HttpClient httpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 发送POST请求（不带token，不带参数）
     *
     * @param url         请求URL
     * @param requestBody 请求体对象
     * @return 响应字符串
     */
    public static String post(String url, Object requestBody) {
        return post(url, requestBody, null, null);
    }

    /**
     * 发送POST请求（带token，不带参数）
     *
     * @param url         请求URL
     * @param requestBody 请求体对象
     * @param token       认证token
     * @return 响应字符串
     */
    public static String post(String url, Object requestBody, String token) {
        return post(url, requestBody, token, null);
    }

    /**
     * 发送POST请求（带token，带参数）
     *
     * @param url         请求URL
     * @param requestBody 请求体对象
     * @param token       认证token
     * @param params      请求参数
     * @return 响应字符串
     */
    public static String post(String url, Object requestBody, String token, Map<String, String> params) {
        try {
            String jsonBody = objectMapper.writeValueAsString(requestBody);

            // 构建带参数的URL
            String fullUrl = buildUrlWithParams(Constants.SYSTEM_BACKEND_URL + url, params);

            HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                    .uri(URI.create(fullUrl))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
                    .timeout(Duration.ofSeconds(30));

            // 如果提供了token，则添加到请求头中
            if (token != null && !token.isEmpty()) {
                requestBuilder.header("Authorization", "Bearer " + token);
            }

            HttpRequest request = requestBuilder.build();

            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() == 200) {
                return response.body();
            } else {
                String errorMessage = "请求失败，状态码: " + response.statusCode()
                        + "\n响应内容: " + response.body();
                log.error(errorMessage);
                return errorMessage;
            }
        } catch (Exception e) {
            log.error("HTTP请求异常", e);
            return "请求异常: " + e.getMessage();
        }
    }

    /**
     * 发送GET请求（不带token，不带参数）
     *
     * @param url 请求URL
     * @return 响应字符串
     */
    public static String get(String url) {
        return get(url, null, null);
    }

    /**
     * 发送GET请求（带token，不带参数）
     *
     * @param url   请求URL
     * @param token 认证token
     * @return 响应字符串
     */
    public static String get(String url, String token) {
        return get(url, token, null);
    }

    /**
     * 发送GET请求（带token，带参数）
     *
     * @param url    请求URL
     * @param token  认证token
     * @param params 请求参数
     * @return 响应字符串
     */
    public static String get(String url, String token, Map<String, String> params) {
        try {
            // 构建带参数的URL
            String fullUrl = buildUrlWithParams(Constants.SYSTEM_BACKEND_URL + url, params);

            HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                    .uri(URI.create(fullUrl))
                    .header("Content-Type", "application/json")
                    .timeout(Duration.ofSeconds(30))
                    .GET();

            // 如果提供了token，则添加到请求头中
            if (token != null && !token.isEmpty()) {
                requestBuilder.header("Authorization", "Bearer " + token);
            }

            HttpRequest request = requestBuilder.build();

            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() == 200) {
                return response.body();
            } else {
                String errorMessage = "请求失败，状态码: " + response.statusCode()
                        + "\n响应内容: " + response.body();
                log.error(errorMessage);
                return errorMessage;
            }
        } catch (Exception e) {
            log.error("HTTP请求异常", e);
            return "请求异常: " + e.getMessage();
        }
    }
    
    /**
     * 发送PUT请求（不带token，不带参数）
     *
     * @param url         请求URL
     * @param requestBody 请求体对象
     * @return 响应字符串
     */
    public static String put(String url, Object requestBody) {
        return put(url, requestBody, null, null);
    }

    /**
     * 发送PUT请求（带token，不带参数）
     *
     * @param url         请求URL
     * @param requestBody 请求体对象
     * @param token       认证token
     * @return 响应字符串
     */
    public static String put(String url, Object requestBody, String token) {
        return put(url, requestBody, token, null);
    }

    /**
     * 发送PUT请求（带token，带参数）
     *
     * @param url         请求URL
     * @param requestBody 请求体对象
     * @param token       认证token
     * @param params      请求参数
     * @return 响应字符串
     */
    public static String put(String url, Object requestBody, String token, Map<String, String> params) {
        try {
            String jsonBody = objectMapper.writeValueAsString(requestBody);

            // 构建带参数的URL
            String fullUrl = buildUrlWithParams(Constants.SYSTEM_BACKEND_URL + url, params);

            HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                    .uri(URI.create(fullUrl))
                    .header("Content-Type", "application/json")
                    .PUT(HttpRequest.BodyPublishers.ofString(jsonBody))
                    .timeout(Duration.ofSeconds(30));

            // 如果提供了token，则添加到请求头中
            if (token != null && !token.isEmpty()) {
                requestBuilder.header("Authorization", "Bearer " + token);
            }

            HttpRequest request = requestBuilder.build();

            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() == 200) {
                return response.body();
            } else {
                String errorMessage = "请求失败，状态码: " + response.statusCode()
                        + "\n响应内容: " + response.body();
                log.error(errorMessage);
                return errorMessage;
            }
        } catch (Exception e) {
            log.error("HTTP请求异常", e);
            return "请求异常: " + e.getMessage();
        }
    }
    
    /**
     * 发送DELETE请求（不带token，不带参数）
     *
     * @param url 请求URL
     * @return 响应字符串
     */
    public static String delete(String url) {
        return delete(url, null, null);
    }

    /**
     * 发送DELETE请求（带token，不带参数）
     *
     * @param url   请求URL
     * @param token 认证token
     * @return 响应字符串
     */
    public static String delete(String url, String token) {
        return delete(url, token, null);
    }

    /**
     * 发送DELETE请求（带token，带参数）
     *
     * @param url    请求URL
     * @param token  认证token
     * @param params 请求参数
     * @return 响应字符串
     */
    public static String delete(String url, String token, Map<String, String> params) {
        try {
            // 构建带参数的URL
            String fullUrl = buildUrlWithParams(Constants.SYSTEM_BACKEND_URL + url, params);

            HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                    .uri(URI.create(fullUrl))
                    .header("Content-Type", "application/json")
                    .timeout(Duration.ofSeconds(30))
                    .DELETE();

            // 如果提供了token，则添加到请求头中
            if (token != null && !token.isEmpty()) {
                requestBuilder.header("Authorization", "Bearer " + token);
            }

            HttpRequest request = requestBuilder.build();

            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() == 200) {
                return response.body();
            } else {
                String errorMessage = "请求失败，状态码: " + response.statusCode()
                        + "\n响应内容: " + response.body();
                log.error(errorMessage);
                return errorMessage;
            }
        } catch (Exception e) {
            log.error("HTTP请求异常", e);
            return "请求异常: " + e.getMessage();
        }
    }

    /**
     * 构建带参数的URL
     *
     * @param baseUrl 基础URL
     * @param params  参数映射
     * @return 带参数的完整URL
     */
    private static String buildUrlWithParams(String baseUrl, Map<String, String> params) {
        if (params == null || params.isEmpty()) {
            return baseUrl;
        }

        StringBuilder urlBuilder = new StringBuilder(baseUrl);
        boolean isFirst = true;

        // 添加查询参数
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (isFirst) {
                urlBuilder.append("?");
                isFirst = false;
            } else {
                urlBuilder.append("&");
            }

            // 对参数进行URL编码
            urlBuilder.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8))
                    .append("=")
                    .append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
        }

        return urlBuilder.toString();
    }
}